import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

paused = False

# init chart
fig, ax = plt.subplots()
line, = plt.plot([], [], lw=2)

# 设置边界
#ax.set_xlim(0, 100)
#ax.set_ylim(-1, 1)

global_x_min = 0
global_x_max = 1
global_y_min = -0.1
global_y_max = 0.1

ax.set_xlim(global_x_min, global_x_max)
ax.set_ylim(global_y_min, global_y_max)

# 自动调节坐标轴
def reset_limits(x, y):
    global global_x_min, global_x_max, global_y_min, global_y_max
    reset_x = True
    reset_y = True
    if x < global_x_min:
        global_x_min *= 2
    elif x > global_x_max:
        global_x_max *= 2
    else:
        reset_x = False

    if y < global_y_min:
        global_y_min *= 2
    elif y > global_y_max:
        global_y_max *= 2
    else:
        reset_y = False
    
    if reset_x or reset_y:
        if reset_x:
            ax.set_xlim(global_x_min, global_x_max)
        if reset_y:
            ax.set_ylim(global_y_min, global_y_max)
        # 整个窗口刷新
        fig.canvas.draw_idle()


# 初始化背景
def init():
    line.set_data([], [])
    return line,

def update(frame):
    #print(frame)
    x = frame
    y = np.sin(x)
    xdata.append(x)
    ydata.append(y)
    line.set_data(xdata, ydata)

    #print(min(xdata) - 1, max(xdata) + 1)
    #plt.xlim(min(xdata) - 1, max(xdata) + 1)
    #plt.ylim(min(ydata) - 1, max(ydata) + 1)
    #ax.set_xlim(min(xdata)-1, max(xdata)+1, auto = True)
    #ax.set_ylim(min(ydata)-1, max(ydata)+1, auto = True)
    #ax.relim()
    reset_limits(x, y)
    
    return line,

xdata, ydata = [], []

ax.set_title('Simple plot')
plt.xlabel('x_axis')
plt.ylabel('y axis')
plt.grid(visible = True, ls = '--', alpha = 0.6, c = 'gray')

def toggle_pause(self, *args, **kwargs):
    global paused
    if paused:
        ani.resume()
        paused = False
    else:
        ani.pause()
        paused = True


fig.canvas.mpl_connect('button_press_event', toggle_pause)

# 使用 Animation.pause () 方法暂停动画。 使用 Animation.resume () 方法恢复动画。
# blit如果为True，则只绘制更新过的部分，可以提高性能，如果为False，则每次都会重新绘制整个图表。
ani = FuncAnimation(fig, update, interval = 1000, frames=np.linspace(0, 10, 200),
            init_func=init, blit=True)
#plt.autoscale(enable = True, axis = 'both', tight = None)
plt.show()
